<?php
/**
 * 把一个关联数组转化成为一个对象
 */
class ArrayToObject implements Iterator{
    protected $items = array();
    protected $keys = array();
    protected $pos = 0;

    public function __construct(&$arr)
    {
        foreach($arr as $key => &$val){
            if(is_array($val)){
                $this->items[$key] = new ArrayToObject($val);
            }else{
                $this->items[$key] = $val;
            }
        }

        $this->keys = array_keys($arr);
    }

    public function dump($notEcho=false)
    {
        return var_export($this->items, $notEcho);
    }

    public function __set($key, $val)
    {
        $this->items[$key] = $val;
    }

    public function __get($key)
    {
        if(preg_match("/^_[0-9]+$/", $key))
            $key = ltrim($key, "_");
        return $this->items[$key];
    }

    public function toArray()
    {
        return $this->items;
    }

    public function rewind()
    {
        $this->pos = 0;
    }

    public function current()
    {
        return $this->items[$this->keys[$this->pos]];
    }

    public function key()
    {
        return $this->keys[$this->pos];
    }

    public function valid()
    {
        return isset($this->keys[$this->pos]);
    }

    public function next()
    {
        return $this->items[$this->keys[++$this->pos]];
    }
}

